﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Helpers
{
    public class DownloadHtmlHelper
    {
        public HttpHelper httpHelper;
        
        /// <summary>
        /// 将去掉指定的字符
        /// </summary>
        public string[] oldValueArray { get; set; }
        /// <summary>
        /// 限定范围
        /// </summary>
        public string pattern2 { get; set; }
        /// <summary>
        /// 默认编码
        /// </summary>
        public string encoding { get; set; }


        public DownloadHtmlHelper()
        {
            oldValueArray = new string[] { " ", "\r", "\n", "\t", "&nbsp;" };
            pattern2 = "(.*)";
            encoding = "utf-8";
            httpHelper = HttpHelper.Instance;
        }

        public string GetHtml(string url)
        {
            return httpHelper.Get(url, encoding).Replace(oldValueArray, "");
        }

        public string PostHtml(string url, List<KeyValuePair<string, string>> paramList)
        {
            return httpHelper.Post(url, paramList).Replace(oldValueArray, "");
        }

        public List<T> GetHtmlAndRegax<T>(string url, string pattern) where T : new()
        {
            string html = GetHtml(url);
            html = Regex.Match(html, pattern2).Groups[1].Value;
            return Convert<T>(Regex.Matches(html, pattern));
        }

        public List<T> PostHtmlAndRegax<T>(string url, List<KeyValuePair<string, string>> paramList, string pattern) where T : new()
        {
            string html = PostHtml(url, paramList);
            html = Regex.Match(html, pattern2).Groups[1].Value;
            return Convert<T>(Regex.Matches(html, pattern));
        }

        private List<T> Convert<T>(MatchCollection matches) where T : new()
        {
            List<T> result = new List<T>();
            Type type = typeof(T);
            foreach (Match match in matches)
            {
                T entity = new T();
                foreach (var prop in type.GetProperties())
                {
                    if (match.Groups[prop.Name].Value.IsNotNullOrEmpty())
                        prop.SetValue(entity, match.Groups[prop.Name].Value, null);
                }
                result.Add(entity);
            }
            return result;
        }
    }
}
